<?php

/**
 * @Author: Wang Chunsheng 2192138785@qq.com
 * @Date:   2020-03-03 06:42:36
 * @Last Modified by:   Wang Chunsheng 2192138785@qq.com
 * @Last Modified time: 2020-03-29 17:09:03
 */


use common\widgets\MyActiveForm;
use yii\helpers\Html;
use yii\bootstrap\Tabs;
use common\models\DdCategory;
use kartik\tabs\TabsX;
use richardfan\widget\JSRegister;
use yii\helpers\Url;

/* @var $this yii\web\View */
/* @var $model common\models\DdGoods */

$this->title = '添加 Dd Goods';
$this->params['breadcrumbs'][] = ['label' => 'Dd Goods', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>



<style type="text/css">
    .spectable td,
    .spectable th {
        border: 1px solid #ccc;
        vertical-align: middle;
        text-align: center;
    }

    .spectable th {
        font-weight: bold;
    }

    .spectableinput {
        text-align: center;
    }

    .f {
        border-color: #b94a48;
        -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
        -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    }

    .table.table-bordered tr th,
    .table.table-bordered tr td {
        overflow: hidden;
        text-overflow: ellipsis;
    }

    a.deleteParam {
        display: block;
        text-align: center;
        line-height: 16px;
        font-size: 22px;
    }

    .spec_item {
        border-radius: 3px;
        border: 1px solid #ccc;
    }
</style>
<ul class="nav nav-tabs">
    <li class="active">
        <?= Html::a('添加 Dd Goods', ['create'], ['class' => 'btn btn-primary']) ?>
    </li>
    <li>
        <?= Html::a('Dd Goods管理', ['index'], ['class' => '']) ?>
    </li>
</ul>
<div class="firetech-main" style="margin-top:20px;">
    <div class="panel panel-default">
        <div class="box-body">
            <div class="dd-goods-create" style="padding-left:10px;padding-right:10px;">
                <?php $form = MyActiveForm::begin([
                    'options' => ['enctype' => 'multipart/form-data'],
                    'method' => 'post',
                    'enableAjaxValidation' => true,
                    'validationUrl' => Url::to(['validate']),     //数据异步校验
                ]); ?>

                <?php
                echo TabsX::widget([
                    'position' => TabsX::POS_ABOVE,
                    'align' => TabsX::ALIGN_LEFT,
                    'items' => [
                        [
                            'label' => '基础信息',
                            'content' => $this->render('goods_base', [
                                'model' => $model,
                                'form' => $form,
                                'catedata' => $catedata,
                                'modelcate' => $modelcate,
                                'Helper' => $Helper,

                            ]),
                            'active' => true
                        ],
                        [
                            'label' => '商品详情',
                            'content' => $this->render('goods_detail', [
                                'model' => $model,
                                'form' => $form,

                            ]),
                            'headerOptions' => ['style' => 'font-weight:bold'],

                        ],
                        [
                            'label' => '商品规格',
                            'content' => $this->render('goods_spec', [
                                'model' => $model,
                                'form' => $form,
                                'specitem' => $specitem,
                                'spec' => $spec,
                                'specv' => $specv,
                                'spec_item_thumbs' => $spec_item_thumbs,
                                'spec_item_shows' => $spec_item_shows,
                                'html' => $html,
                            ]),
                        ],
                        [
                            'label' => '商品属性',
                            'content' => $this->render('goods_options', [
                                'model' => $model,
                                'form' => $form,
                                'params' => $params

                            ]),
                        ],
                    ],
                ]);

                ?>
                <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">

                    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">

                    </div>


                    <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 ">
                        <?= Html::submitButton('保存', ['class' => 'btn btn-success btn-block']) ?>
                    </div>
                </div>

                <?php MyActiveForm::end(); ?>

            </div>
        </div>
    </div>
</div>
<?php JSRegister::begin([
    'key' => '3445'
]); ?>
<script>
    // 打开商品规格
    $("#ddgoods-spec_type").click(function() {
        var obj = $(this);
        if (obj.get(0).checked) {
            $("#tboption").show();
        } else {
            $("#tboption").hide();
        }
    });
    //分类
    $("#classsearch-cocate_id").change(function() {
        var cocateId = $(this).val(); //获取一级目录的值
        // $("#classsearch-course_id").html("<option value=\"\">选择二级分类</option>");//二级显示目录标签
        console.log(cocateId)
        if (cocateId > 0) {
            getCourse(cocateId); //查询二级目录的方法
        }
    });

    function getCourse(cocateId) {
        var href = "<?= Url::to(['/diandi_shop/goods/dd-category/childcate']) ?>"; //请求的地址
        $.ajax({
            "type": "post",
            "url": href,
            "data": {
                parent_id: cocateId,
                type: "course"
            }, //所需参数和类型
            success: function(d) {
                var htmls = '';
                $.each(d, function(index, item) {
                    htmls += '<option value="' + item.category_id + '">' + item.name + '</option>';

                })
                console.log(htmls)
                $("#classsearch-course_id").append(htmls); //返回值输出
            }
        });
    }

    // 添加规格项
    $('#specs').on('click', '.add-specitem', function() {
        specid = $(this).data('specid')
        $("#add-specitem-" + specid).html("正在处理...").attr("disabled", "true");
        var url = "<?php echo Url::to('specitem'); ?>";
        $.ajax({
            "url": url,
            type: 'POST',
            'data': {
                specid: specid,
            },
            success: function(data) {
                clas = $(this).attr('class')
                // return false;

                // console.log($("#spec_item_" + specid).html());
                $("#add-specitem-" + specid).html('<i class="fa fa-plus"></i> 添加规格项').removeAttr("disabled");
                // $('#spec_item_' + specid).appendTo(data);
                $(data).appendTo('#spec_item_' + specid);

                var len = $("#spec_" + specid + " .spec_item_title").length - 1;
                $("#spec_" + specid + " .spec_item_title:eq(" + len + ")").focus();
                // window.optionchanged = true;

            }
        });

        $('#specs').on('click', '.removeSpec', function() {
            specid = $(this).data('specid')
            console.log(specid);
            if (confirm('确认要删除此规格?')) {
                $("#spec_" + specid).remove();
                window.optionchanged = true;

            }
        });
    })

    // 添加规格
    $('#add-spec').click(function() {
        $("#add-spec").html("正在处理...").attr("disabled", "true").toggleClass("btn-primary");
        var url = "<?php echo Url::to('spec'); ?>";
        $.ajax({
            "url": url,
            success: function(data) {
                $("#add-spec").html('<i class="fa fa-plus"></i> 添加规格').removeAttr("disabled").toggleClass("btn-primary");;
                $('#specs').append(data);
                var len = $(".add-specitem").length - 1;
                $(".add-specitem:eq(" + len + ")").focus();
                window.optionchanged = true;
            }
        });
    });

    $('#calcref').on('click', function() {


        if ($(".spec_item_title").length == 0) {
            alert('请添加每种规格下的规格项');
        }

        window.optionchanged = false;
        var html = '<table class="table table-bordered table-condensed"><thead><tr class="active">';
        var specs = [];
        $(".spec_item").each(function(i) {
            var _this = $(this);

            var spec = {
                id: _this.find(".spec_id").val(),
                title: _this.find(".spec_title").val()
            };

            var items = [];
            _this.find(".spec_item_item").each(function() {
                var __this = $(this);
                var item = {
                    id: __this.find(".spec_item_id").val(),
                    title: __this.find(".spec_item_title").val(),
                    show: __this.find(".spec_item_show").get(0).checked ? "1" : "0"
                }
                items.push(item);
            });
            spec.items = items;
            specs.push(spec);
        });


        var len = specs.length;
        var newlen = 1; //多少种组合
        var h = new Array(len); //显示表格二维数组
        var rowspans = new Array(len); //每个列的rowspan
        for (var i = 0; i < len; i++) {
            //表头
            html += "<th style='width:80px;' class='active'>" + specs[i].title + "</th>";

            //计算多种组合
            var itemlen = specs[i].items.length;
            if (itemlen <= 0) {
                itemlen = 1
            };
            newlen *= itemlen;

            //初始化 二维数组
            h[i] = new Array(newlen);
            for (var j = 0; j < newlen; j++) {
                h[i][j] = new Array();
            }
            //计算rowspan
            var l = specs[i].items.length;
            rowspans[i] = 1;
            for (j = i + 1; j < len; j++) {
                rowspans[i] *= specs[j].items.length;
            }
        }

        html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">库存</div><div class="input-group"><input type="text" class="form-control option_stock_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down setCol" title="批量设置" data-type="option_stock"></a></span></div></div></th>';
        html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">销售价格</div><div class="input-group"><input type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down setCol" title="批量设置" data-type="option_marketprice"></a></span></div></div></th>';
        html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">市场价格</div><div class="input-group"><input type="text" class="form-control option_productprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down setCol" title="批量设置" data-type="option_productprice"></a></span></div></div></th>';
        html += '<th class="danger" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">成本价格</div><div class="input-group"><input type="text" class="form-control option_costprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down setCol" title="批量设置" data-type="option_costprice"></a></span></div></div></th>';
        html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">重量（克）</div><div class="input-group"><input type="text" class="form-control option_weight_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down setCol" title="批量设置" data-type="option_weight"></a></span></div></div></th>';
        html += '</tr></thead>';

        for (var m = 0; m < len; m++) {
            var k = 0,
                kid = 0,
                n = 0;
            for (var j = 0; j < newlen; j++) {
                var rowspan = rowspans[m]; //9
                if (j % rowspan == 0) {
                    h[m][j] = {
                        title: specs[m].items[kid].title,
                        html: "<td rowspan='" + rowspan + "'>" + specs[m].items[kid].title + "</td>\r\n",
                        id: specs[m].items[kid].id
                    };
                    //	k++; if(k>specs[m].items.length-1) { k=0; }
                } else {
                    h[m][j] = {
                        title: specs[m].items[kid].title,
                        html: "",
                        id: specs[m].items[kid].id
                    };
                }
                n++;
                if (n == rowspan) {
                    kid++;
                    if (kid > specs[m].items.length - 1) {
                        kid = 0;
                    }
                    n = 0;
                }
            }
        }

        var hh = "";
        for (var i = 0; i < newlen; i++) {
            hh += "<tr>";
            var ids = [];
            var titles = [];
            for (var j = 0; j < len; j++) {
                hh += h[j][i].html; //每一行的每个规格项列
                ids.push(h[j][i].id);
                titles.push(h[j][i].title);
            }
            ids = ids.join('_');
            titles = titles.join('+');

            var val = {
                id: "",
                title: titles,
                stock: "",
                costprice: "",
                productprice: "",
                marketprice: "",
                weight: ""
            };
            if ($(".option_id_" + ids).length > 0) {
                val = {
                    id: $(".option_id_" + ids + ":eq(0)").val(),
                    title: titles,
                    stock: $(".option_stock_" + ids + ":eq(0)").val(),
                    costprice: $(".option_costprice_" + ids + ":eq(0)").val(),
                    productprice: $(".option_productprice_" + ids + ":eq(0)").val(),
                    marketprice: $(".option_marketprice_" + ids + ":eq(0)").val(),
                    weight: $(".option_weight_" + ids + ":eq(0)").val()
                }
            }
            hh += '<td class="info">'
            hh += '<input name="option_stock_' + ids + '[]"type="text" class="form-control option_stock option_stock_' + ids + '" value="' + (val.stock == 'undefined' ? '' : val.stock) + '"/></td>';
            hh += '<input name="option_id_' + ids + '[]"type="hidden" class="form-control option_id option_id_' + ids + '" value="' + (val.id == 'undefined' ? '' : val.id) + '"/>';
            hh += '<input name="option_ids[]"type="hidden" class="form-control option_ids option_ids_' + ids + '" value="' + ids + '"/>';
            hh += '<input name="option_title_' + ids + '[]"type="hidden" class="form-control option_title option_title_' + ids + '" value="' + (val.title == 'undefined' ? '' : val.title) + '"/></td>';
            hh += '</td>';
            hh += '<td class="success"><input name="option_marketprice_' + ids + '[]" type="text" class="form-control option_marketprice option_marketprice_' + ids + '" value="' + (val.marketprice == 'undefined' ? '' : val.marketprice) + '"/></td>';
            hh += '<td class="warning"><input name="option_productprice_' + ids + '[]" type="text" class="form-control option_productprice option_productprice_' + ids + '" " value="' + (val.productprice == 'undefined' ? '' : val.productprice) + '"/></td>';
            hh += '<td class="danger"><input name="option_costprice_' + ids + '[]" type="text" class="form-control option_costprice option_costprice_' + ids + '" " value="' + (val.costprice == 'undefined' ? '' : val.costprice) + '"/></td>';
            hh += '<td class="info"><input name="option_weight_' + ids + '[]" type="text" class="form-control option_weight option_weight_' + ids + '" " value="' + (val.weight == 'undefined' ? '' : val.weight) + '"/></td>';
            hh += "</tr>";
        }
        html += hh;
        html += "</table>";
        $("#options").html(html);
    });

    $('#options').on('click', '.setCol', function() {
        var cls = $(this).data('type');

        console.log('.' + cls + '_all')
        $("." + cls).val($('.' + cls + '_all').val());
    })

    /* 添加属性 */
    $('#add-param').click(function() {
        var url = "<?php echo Url::to('param'); ?>";
        $.ajax({
            "url": url,
            success: function(data) {
                $('#param-items').append(data);
            }
        });
        return;
    })

    $('#param-items').on('click', '.deleteParam', function() {
        $(this).parent().parent().remove();
    })

    // 获取长度为len的随机字符串
    function _getRandomString(len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
        var maxPos = $chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }
</script>

<?php JSRegister::end(); ?>